﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using MyHealthOnline.ServiceReference1;
using System.Web.Security;//FormsAuthentication object exists in following namespace.

namespace MyHealthOnline.Account
{
    public partial class Login : System.Web.UI.Page
    {
        DropDownList rolUtilizator;
        protected void Page_Load(object sender, EventArgs e)
        {
            RegisterHyperLink.NavigateUrl = "~/Account/Register.aspx?ReturnUrl=" + HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
            
            rolUtilizator = LoginUser.FindControl("userRoleDropDownList") as DropDownList;
        }


/// <summary>
/// Autentificare utilizator
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
        //protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
        //{
        //    // just hard code the username for this demo
        //    // in real scenario you should call your object and validate username and password againt the database or whichever data source you are using
        //    //string localUserName = "user";
        //    //string localPassword = "password";
        //    //string role = userRoleDropDownList.SelectedValue.ToString();
            
        //    string username = LoginUser.UserName.Trim(); //email
        //    string role = rolUtilizator.SelectedValue.ToString();
        //    //string role = "Administrator";
        //    bool rememberUserName = LoginUser.RememberMeSet;
        //    WebServiceHO webService = new WebServiceHO();
        //    bool validMail = webService.verificaSintaxaMail(username);
        //    if (validMail)
        //    {
        //        Session.Clear();

        //        string password = LoginUser.Password.Trim();
                
               
        //        int i = webService.LoginByUsernameAndPassword(role, username, password);

        //        if (i == 0)//DATELE INTRODUSE NU SUNT CORECTE
        //        {
        //            Response.Redirect("~/Default.aspx");
        //            LoginUser.FailureText = "Login failed. Please try again!";
        //        }
        //        else
        //            if (i == 1) //datele de logare sunt valide
        //            {
        //                FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
        //                    1, // Ticket version
        //                    username,// Username to be associated with this ticket
        //                    DateTime.Now, // Date/time ticket was issued
        //                    DateTime.Now.AddMinutes(50), // Date and time the cookie will expire
        //                    rememberUserName, // if user has chcked rememebr me then create persistent cookie
        //                    role, // store the user data, in this case roles of the user
        //                    FormsAuthentication.FormsCookiePath); // Cookie path specified in the web.config file in <Forms> tag if any.

        //                // To give more security it is suggested to hash it
        //                string hashCookies = FormsAuthentication.Encrypt(ticket);
        //                HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies); // Hashed ticket

        //                // Add the cookie to the response, user browser
        //                Response.Cookies.Add(cookie);

        //                // Get the requested page from the url
        //                string returnUrl = Request.QueryString["ReturnUrl"];

        //                // check if it exists, if not then redirect to default page
        //                if (returnUrl == null)
        //                {
        //                    switch (role)
        //                        {
        //                            case "Patient": returnUrl = "~/Pacient/Patient.aspx";
        //                                            break;
        //                            case "Administrator": returnUrl = "~/Administrator/AdminPageContent.aspx";
        //                                                  break;
        //                            case "Specialist": returnUrl = "~/Specialist/Specialist.aspx";
        //                                               break;
        //                            default: break;
        //                        }
        //                }
        //                Response.Redirect(returnUrl);
        //            }
        //    }
        //}
        protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
        {
            // just hard code the username for this demo
            // in real scenario you should call your object and validate username and password againt the database or whichever data source you are using
            //string localUserName = "user";
            //string localPassword = "password";
            //string role = userRoleDropDownList.SelectedValue.ToString();

            string username = LoginUser.UserName.Trim(); //email
            string role = rolUtilizator.SelectedValue.ToString();
            //string role = "Administrator";
            bool rememberUserName = LoginUser.RememberMeSet;
            WebServiceHO webService = new WebServiceHO();
            bool validMail = webService.verificaSintaxaMail(username);
            if (validMail)
            {
                string password = LoginUser.Password.Trim();


                int i = webService.LoginByUsernameAndPassword(role, username, password);
                // Get the requested page from the url
                string returnUrl = Request.QueryString["ReturnUrl"];

                if (i == 0)//DATELE INTRODUSE NU SUNT CORECTE
                {
                    Response.Redirect("~/Default.aspx");
                    LoginUser.FailureText = "Login failed. Please try again!";
                }
                else
                    if (i == 1) //datele de logare sunt valide
                    {
                        switch (role)
                        {
                            case "Patient":
                                int idPatient = webService.getIdPatient(username);// .get_id(Session["Username"].ToString());
                                Session["id"] = idPatient;
                                //Response.Redirect(string.Format("~/Home.aspx?UserName={0}&Rol={1}", nume_utilizator, rol));
                                if (returnUrl == null) returnUrl = "~/Patient/Patient.aspx";

                                break;
                            case "Administrator":
                                if (returnUrl == null) returnUrl = "~/Administrator/AdminPageContent.aspx";
                                //string idAdministrator = webService.getIdAdmin(Session["username"].ToString());
                                //Session["id"] = idAdministrator;
                                //Response.Redirect("Administrator.aspx");

                                break;
                            case "Specialist":
                                string idSpecialist = webService.getIdSpecialist(username);
                                Session["id"] = idSpecialist;
                                if (returnUrl == null) returnUrl = "~/Specialist/Specialist.aspx";

                                break;
                            default: break;
                        }
                        FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                            1, // Ticket version
                            username,// Username to be associated with this ticket
                            DateTime.Now, // Date/time ticket was issued
                            DateTime.Now.AddMinutes(50), // Date and time the cookie will expire
                            rememberUserName, // if user has chcked rememebr me then create persistent cookie
                            role, // store the user data, in this case roles of the user
                            FormsAuthentication.FormsCookiePath); // Cookie path specified in the web.config file in <Forms> tag if any.

                        // To give more security it is suggested to hash it
                        string hashCookies = FormsAuthentication.Encrypt(ticket);
                        HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashCookies); // Hashed ticket

                        // Add the cookie to the response, user browser
                        Response.Cookies.Add(cookie);


                        // check if it exists, if not then redirect to default page
                        Response.Redirect(returnUrl);
                    }
            }
        }
    }
}
